﻿package cn.poco.pepsi.util;

import java.io.FileNotFoundException;
import java.lang.ref.SoftReference;
import java.util.HashMap;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

public class AsyncImageLoader {

	private HashMap<String, SoftReference<Bitmap>> imageCache;
	private static boolean isCompress = false;
	private static int size = 1;

	public AsyncImageLoader() {
		imageCache = new HashMap<String, SoftReference<Bitmap>>();
	}

	public Bitmap loadDrawable(final String imageUrl, final ImageCallback imageCallback, final Context context,
			boolean isCompres, int size) {
		AsyncImageLoader.isCompress = isCompres;
		AsyncImageLoader.size = size;
		if (imageCache.containsKey(imageUrl)) {
			SoftReference<Bitmap> softReference = imageCache.get(imageUrl);
			Bitmap drawable = softReference.get();
			if (drawable != null) {
				return drawable;
			}
		}

		final Handler handler = new Handler() {
			public void handleMessage(Message message) {
				imageCallback.imageLoaded((Bitmap) message.obj, imageUrl);
			}
		};

		new Thread() {
			@Override
			public void run() {
				Bitmap drawable;
				try {
					drawable = loadImageFromUrl(imageUrl, context);
					if (drawable != null) {
						imageCache.put(imageUrl, new SoftReference<Bitmap>(drawable));
						Message message = handler.obtainMessage(0, drawable);
						handler.sendMessage(message);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
		return null;
	}

	public static Bitmap loadImageFromUrl(String url, Context context) throws Exception {
		Bitmap bitMap = null;
		try {
			String fString = new DownloadImage(context).download(url);
			if (isCompress) {
				bitMap = compress(fString, size);
			} else {
				bitMap = BitmapFactory.decodeFile(fString);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			Toast.makeText(context, "未挂载SD卡", Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			e.printStackTrace();

		}
		return bitMap;
	}

	public static Bitmap compress(String url, int size) {
		Bitmap bitMapCompressed = null;
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		bitMapCompressed = BitmapFactory.decodeFile(url, options); // 此时返回bm为空
		options.inJustDecodeBounds = false;
		int be = (int) (options.outHeight / (float) size);
		if (be <= 0)
			be = 1;
		options.inSampleSize = be;
		bitMapCompressed = BitmapFactory.decodeFile(url, options);
		return bitMapCompressed;
	}

	public interface ImageCallback {
		public void imageLoaded(Bitmap imageDrawable, String imageUrl);
	}

}
